<?php
class ControllerSaleOrderDistributor extends Controller {
    private $error = array();

    public function index() {
        $this->load->language('sale/order');

        $this->document->setTitle($this->language->get('heading_title'));

        $this->load->model('sale/order');

        $this->getList();
    }

    protected function getList() {
        if (isset($this->request->get['filter_order_id'])) {
            $filter_order_id = $this->request->get['filter_order_id'];
        } else {
            $filter_order_id = null;
        }

        if (isset($this->request->get['filter_customer'])) {
            $filter_customer = $this->request->get['filter_customer'];
        } else {
            $filter_customer = null;
        }

        if (isset($this->request->get['filter_order_status'])) {
            $filter_order_status = $this->request->get['filter_order_status'];
        } else {
            $filter_order_status = null;
        }

        if (isset($this->request->get['filter_total'])) {
            $filter_total = $this->request->get['filter_total'];
        } else {
            $filter_total = null;
        }

        if (isset($this->request->get['filter_is_pay'])) {
            $filter_is_pay = $this->request->get['filter_is_pay'];
        } else {
            $filter_is_pay = 3;
        }

        if (isset($this->request->get['filter_date_added'])) {
            $filter_date_added = $this->request->get['filter_date_added'];
        } else {
            $filter_date_added = null;
        }

        if (isset($this->request->get['filter_date_modified'])) {
            $filter_date_modified = $this->request->get['filter_date_modified'];
        } else {
            $filter_date_modified = null;
        }

        if (isset($this->request->get['filter_date_start'])) {
            $filter_date_start = $this->request->get['filter_date_start'];
        } else {
            $filter_date_start = null;
        }

        if (isset($this->request->get['filter_date_end'])) {
            $filter_date_end = $this->request->get['filter_date_end'];
        } else {
            $filter_date_end = null;
        }

        if (isset($this->request->get['filter_logcenter'])) {
            $filter_logcenter = $this->request->get['filter_logcenter'];
        } else {
            $filter_logcenter = null;
        }

        if (isset($this->request->get['filter_recommended_code'])) {
            $filter_recommended_code = (string)$this->request->get['filter_recommended_code'];
        } else {
            $filter_recommended_code = null;
        }

        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'o.order_id';
        }

        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            $order = 'DESC';
        }

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        $url = '';

        if (isset($this->request->get['filter_order_id'])) {
            $url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
        }

        if (isset($this->request->get['filter_is_pay'])) {
            $url .= '&filter_is_pay=' . $this->request->get['filter_is_pay'];
        }

        if (isset($this->request->get['filter_customer'])) {
            $url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_order_status'])) {
            $url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
        }

        if (isset($this->request->get['filter_total'])) {
            $url .= '&filter_total=' . $this->request->get['filter_total'];
        }

        if (isset($this->request->get['filter_date_added'])) {
            $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
        }

        if (isset($this->request->get['filter_date_start'])) {
            $url .= '&filter_date_start=' . $this->request->get['filter_date_start'];
        }

        if (isset($this->request->get['filter_date_end'])) {
            $url .= '&filter_date_end=' . $this->request->get['filter_date_end'];
        }

        if (isset($this->request->get['filter_date_modified'])) {
            $url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
        }

        if (isset($this->request->get['filter_logcenter'])) {
            $url .= '&filter_logcenter=' . $this->request->get['filter_logcenter'];
        }

        if (isset($this->request->get['filter_recommended_code'])) {
            $url .= '&filter_recommended_code=' . (string)$this->request->get['filter_recommended_code'];
        }

        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }

        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }

        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }

        $data['breadcrumbs'] = array();

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('sale/order_distributor', 'token=' . $this->session->data['token'] . $url, 'SSL')
        );

        $data['invoice'] = $this->url->link('sale/order_distributor/invoice', 'token=' . $this->session->data['token'], 'SSL');
        $data['shipping'] = $this->url->link('sale/order_distributor/shipping', 'token=' . $this->session->data['token'], 'SSL');
        $data['add'] = $this->url->link('sale/order_distributor/add', 'token=' . $this->session->data['token'], 'SSL');

        $data['orders'] = array();

        $filter_data = array(
            'filter_order_id'      => $filter_order_id,
            'filter_is_pay'           => $filter_is_pay,
            'filter_customer'       => $filter_customer,
            'filter_order_status'  => $filter_order_status,
            'filter_total'         => $filter_total,
            'filter_date_added'    => $filter_date_added,
            'filter_date_modified' => $filter_date_modified,
            'filter_logcenter'        => $filter_logcenter,
            'filter_date_start'       => $filter_date_start,
            'filter_date_end'       => $filter_date_end,
            'filter_recommended_code'=> $filter_recommended_code,
            'filter_user_id'       => $this->user->getId(),
            'sort'                 => $sort,
            'order'                => $order,
            'start'                => ($page - 1) * $this->config->get('config_limit_admin'),
            'limit'                => $this->config->get('config_limit_admin')
        );
        $order_total = $this->model_sale_order->getTotalOrders($filter_data);

        $results = $this->model_sale_order->getOrders($filter_data);

        $data['array_is_pay'] = array(
            '3' =>'',
            '0' =>'未付款',
            '1' => '已付款',
            );
        $bill_array = array(
            '1'=>'未开发票',
            '2'=>'已开发票',
            '0'=>'不需要开发票',
            );
        $status_color = array(
            '5' => 'green',
            '2' => 'red',
            '17'=> '#FA0',
            '18'=> 'blue',
            );
        foreach ($results as $result) {
            $data['orders'][] = array(
                'order_id'      => $result['order_id'],
                'shipping_company'=> $result['shipping_company'],
                'difference'    => $result['difference'],
                'customer'      => $result['customer'],
                'status'        => $result['status'],
                'order_status_id'=> $result['order_status_id'],
                'all_color'        => $this->model_sale_order->checkOrderDate($result['date_added'],$result['order_status_id']),
                'payment_method'=> $result['payment_method'],
                'is_pay'        => $result['is_pay']?'已付款':'未付款',
                'status_color'    => $status_color[$result['order_status_id']],
                'shipping_zone' => $result['shipping_zone'],
                'shipping_country'=>$result['shipping_country'],
                'recommended_code'=>$result['recommended_code'],
                'bill_status'    => $bill_array[$result['bill_status']],
                'total'         => $this->currency->format($result['total'], $result['currency_code'], $result['currency_value']),
                'date_added'    => date('Y-m-d H:i', strtotime($result['date_added'])),
                'date_modified' => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                'recommended_name'=> $result['recommended_name'],
                'shipping_code' => $result['shipping_code'],
                'logcenter_name'=>$result['logcenter_name'],
                'view'          => $this->url->link('sale/order_distributor/info', 'token=' . $this->session->data['token'] . '&order_id=' . $result['order_id'] . $url, 'SSL'),
                'edit'          => $this->url->link('sale/order_distributor/edit', 'token=' . $this->session->data['token'] . '&order_id=' . $result['order_id'] . $url, 'SSL'),
            );
        }
    
        $data['heading_title'] = $this->language->get('heading_title');
        
        $data['text_list'] = $this->language->get('text_list');
        $data['text_no_results'] = $this->language->get('text_no_results');
        $data['text_confirm'] = $this->language->get('text_confirm');
        $data['text_missing'] = $this->language->get('text_missing');
        $data['text_loading'] = $this->language->get('text_loading');

        $data['column_order_id'] = $this->language->get('column_order_id');
        $data['column_customer'] = $this->language->get('column_customer');
        $data['column_status'] = $this->language->get('column_status');
        $data['column_total'] = $this->language->get('column_total');
        $data['column_date_added'] = $this->language->get('column_date_added');
        $data['column_date_modified'] = $this->language->get('column_date_modified');
        $data['column_action'] = $this->language->get('column_action');

        $data['entry_return_id'] = $this->language->get('entry_return_id');
        $data['entry_order_id'] = $this->language->get('entry_order_id');
        $data['entry_customer'] = $this->language->get('entry_customer');
        $data['entry_order_status'] = $this->language->get('entry_order_status');
        $data['entry_total'] = $this->language->get('entry_total');
        $data['entry_date_added'] = $this->language->get('entry_date_added');
        $data['entry_date_modified'] = $this->language->get('entry_date_modified');

        $data['button_invoice_print'] = $this->language->get('button_invoice_print');
        $data['button_shipping_print'] = $this->language->get('button_shipping_print');
        $data['button_add'] = $this->language->get('button_add');
        $data['button_edit'] = $this->language->get('button_edit');
        $data['button_delete'] = $this->language->get('button_delete');
        $data['button_filter'] = $this->language->get('button_filter');
        $data['button_view'] = $this->language->get('button_view');
        $data['button_ip_add'] = $this->language->get('button_ip_add');

        $data['token'] = $this->session->data['token'];
        $data['user_group_id'] = $this->session->data['user_group_id'];

        if (isset($this->request->post['selected'])) {
            $data['selected'] = (array)$this->request->post['selected'];
        } else {
            $data['selected'] = array();
        }

        if (isset($this->session->data['error'])) {
            $data['error_warning'] = $this->session->data['error'];
            unset($this->session->data['error']);
        } elseif (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }

        $url = '';

        if (isset($this->request->get['filter_order_id'])) {
            $url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
        }

        if (isset($this->request->get['filter_customer'])) {
            $url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_order_status'])) {
            $url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
        }

        if (isset($this->request->get['filter_total'])) {
            $url .= '&filter_total=' . $this->request->get['filter_total'];
        }

        if (isset($this->request->get['filter_date_added'])) {
            $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
        }

        if (isset($this->request->get['filter_date_modified'])) {
            $url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
        }
        if (isset($this->request->get['filter_recommended_code'])) {
            $url .= '&filter_recommended_code=' . $this->request->get['filter_recommended_code'];
        }

        if ($order == 'ASC') {
            $url .= '&order=DESC';
        } else {
            $url .= '&order=ASC';
        }

        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }
        $data['hand_order'] = $this->url->link('sale/order_distributor/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
        $data['sort_order'] = $this->url->link('sale/order_distributor', 'token=' . $this->session->data['token'] . '&sort=o.order_id' . $url, 'SSL');
        $data['sort_customer'] = $this->url->link('sale/order_distributor', 'token=' . $this->session->data['token'] . '&sort=customer' . $url, 'SSL');
        $data['sort_status'] = $this->url->link('sale/order_distributor', 'token=' . $this->session->data['token'] . '&sort=status' . $url, 'SSL');
        $data['sort_total'] = $this->url->link('sale/order_distributor', 'token=' . $this->session->data['token'] . '&sort=o.total' . $url, 'SSL');
        $data['sort_date_added'] = $this->url->link('sale/order_distributor', 'token=' . $this->session->data['token'] . '&sort=o.date_added' . $url, 'SSL');
        $data['sort_date_modified'] = $this->url->link('sale/order_distributor', 'token=' . $this->session->data['token'] . '&sort=o.date_modified' . $url, 'SSL');

        $url = '';

        if (isset($this->request->get['filter_order_id'])) {
            $url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
        }

        if (isset($this->request->get['filter_is_pay'])) {
            $url .= '&filter_is_pay=' . $this->request->get['filter_is_pay'];
        }

        if (isset($this->request->get['filter_customer'])) {
            $url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_order_status'])) {
            $url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
        }

        if (isset($this->request->get['filter_recommended_code'])) {
            $url .= '&filter_recommended_code=' . $this->request->get['filter_recommended_code'];
        }

        if (isset($this->request->get['filter_total'])) {
            $url .= '&filter_total=' . $this->request->get['filter_total'];
        }

        if (isset($this->request->get['filter_date_added'])) {
            $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
        }

        if (isset($this->request->get['filter_date_modified'])) {
            $url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
        }

        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }

        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }

        $pagination = new Pagination();
        $pagination->total = $order_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_limit_admin');
        $pagination->url = $this->url->link('sale/order_distributor', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

        $data['pagination'] = $pagination->render();

        $data['results'] = sprintf($this->language->get('text_pagination'), ($order_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($order_total - $this->config->get('config_limit_admin'))) ? $order_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $order_total, ceil($order_total / $this->config->get('config_limit_admin')));

        $data['filter_order_id'] = $filter_order_id;
        $data['filter_customer'] = $filter_customer;
        $data['filter_is_pay'] = $filter_is_pay;
        $data['filter_order_status'] = $filter_order_status;
        $data['filter_total'] = $filter_total;
        $data['filter_date_added'] = $filter_date_added;
        $data['filter_date_modified'] = $filter_date_modified;
        $data['filter_date_start'] = $filter_date_start;
        $data['filter_date_end'] = $filter_date_end;
        $data['filter_recommended_code'] = $filter_recommended_code;

        $this->load->model('localisation/order_status');

        $data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();

        $data['sort'] = $sort;
        $data['order'] = $order;
        
        $data['store'] = HTTPS_CATALOG;

        // API login
        $this->load->model('user/api');

        $api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));

        if ($api_info) {
            $data['api_id'] = $api_info['api_id'];
            $data['api_key'] = $api_info['key'];
            $data['api_ip'] = $this->request->server['REMOTE_ADDR'];
        } else {
            $data['api_id'] = '';
            $data['api_key'] = '';
            $data['api_ip'] = '';
        }

        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        $this->response->setOutput($this->load->view('sale/order_list_distributor.tpl', $data));
    }

    public function info() {
        $this->load->model('sale/order');

        if (isset($this->request->get['order_id'])) {
            $order_id = $this->request->get['order_id'];
        } else {
            $order_id = 0;
        }

        $order_info = $this->model_sale_order->getOrder($order_id);
        //if ($order_info) {
        if ($order_info && $order_info['user_id'] == $this->user->getId()) {
            $this->load->language('sale/order');

            $this->document->setTitle($this->language->get('heading_title'));

            $data['heading_title'] = $this->language->get('heading_title');

            $data['text_ip_add'] = sprintf($this->language->get('text_ip_add'), $this->request->server['REMOTE_ADDR']);
            $data['text_order_detail'] = $this->language->get('text_order_detail');
            $data['text_customer_detail'] = $this->language->get('text_customer_detail');
            $data['text_option'] = $this->language->get('text_option');
            $data['text_store'] = $this->language->get('text_store');
            $data['text_date_added'] = $this->language->get('text_date_added');
            $data['text_payment_method'] = $this->language->get('text_payment_method');
            $data['text_shipping_method'] = $this->language->get('text_shipping_method');
            $data['text_customer'] = $this->language->get('text_customer');
            $data['text_customer_group'] = $this->language->get('text_customer_group');
            $data['text_email'] = $this->language->get('text_email');
            $data['text_telephone'] = $this->language->get('text_telephone');
            $data['text_is_invoice_added'] = $this->language->get('text_is_invoice_added');
            $data['text_is_invoice_removed'] = $this->language->get('text_is_invoice_removed');
            $data['text_is_invoice_passed'] = $this->language->get('text_is_invoice_passed');
            $data['text_invoice'] = $this->language->get('text_invoice');
            $data['text_is_invoice'] = $this->language->get('text_is_invoice');
            $data['text_reward'] = $this->language->get('text_reward');
            $data['text_affiliate'] = $this->language->get('text_affiliate');
            $data['text_order'] = sprintf($this->language->get('text_order'), $this->request->get['order_id']);
            $data['text_payment_address'] = $this->language->get('text_payment_address');
            $data['text_shipping_address'] = $this->language->get('text_shipping_address');
            $data['text_comment'] = $this->language->get('text_comment');

            $data['text_account_custom_field'] = $this->language->get('text_account_custom_field');
            $data['text_payment_custom_field'] = $this->language->get('text_payment_custom_field');
            $data['text_shipping_custom_field'] = $this->language->get('text_shipping_custom_field');
            $data['text_browser'] = $this->language->get('text_browser');
            $data['text_ip'] = $this->language->get('text_ip');
            $data['text_forwarded_ip'] = $this->language->get('text_forwarded_ip');
            $data['text_user_agent'] = $this->language->get('text_user_agent');
            $data['text_accept_language'] = $this->language->get('text_accept_language');
            
            $data['text_history'] = $this->language->get('text_history');
            $data['text_history_add'] = $this->language->get('text_history_add');
            $data['text_loading'] = $this->language->get('text_loading');
            $data['text_shipping_telephone'] = $this->language->get('text_shipping_telephone');

            $data['column_sku'] = $this->language->get('column_sku');
            $data['column_product'] = $this->language->get('column_product');
            $data['column_model'] = $this->language->get('column_model');
            $data['column_quantity'] = $this->language->get('column_quantity');
            $data['column_price'] = $this->language->get('column_price');
            $data['column_total'] = $this->language->get('column_total');

            $data['entry_order_status'] = $this->language->get('entry_order_status');
            $data['entry_notify'] = $this->language->get('entry_notify');
            $data['entry_override'] = $this->language->get('entry_override');
            $data['entry_comment'] = $this->language->get('entry_comment');

            $data['entry_sent_comment_to_all'] = $this->language->get('entry_sent_comment_to_all');
            $data['help_sent_comment_to_all'] = $this->language->get('help_sent_comment_to_all');

            $data['help_override'] = $this->language->get('help_override');

            $data['button_invoice_print'] = $this->language->get('button_invoice_print');
            $data['button_shipping_print'] = $this->language->get('button_shipping_print');
            $data['button_edit'] = $this->language->get('button_edit');
            $data['button_cancel'] = $this->language->get('button_cancel');
            $data['button_generate'] = $this->language->get('button_generate');
            $data['button_is_invoice_add'] = $this->language->get('button_is_invoice_add');
            $data['button_is_invoice_remove'] = $this->language->get('button_is_invoice_remove');
            $data['button_reward_add'] = $this->language->get('button_reward_add');
            $data['button_reward_remove'] = $this->language->get('button_reward_remove');
            $data['button_commission_add'] = $this->language->get('button_commission_add');
            $data['button_commission_remove'] = $this->language->get('button_commission_remove');
            $data['button_history_add'] = $this->language->get('button_history_add');
            $data['button_ip_add'] = $this->language->get('button_ip_add');

            $data['tab_history'] = $this->language->get('tab_history');
            $data['tab_additional'] = $this->language->get('tab_additional');

            $data['token'] = $this->session->data['token'];

            $url = '';

            if (isset($this->request->get['filter_order_id'])) {
                $url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
            }

            if (isset($this->request->get['filter_customer'])) {
                $url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
            }

            if (isset($this->request->get['filter_order_status'])) {
                $url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
            }

            if (isset($this->request->get['filter_total'])) {
                $url .= '&filter_total=' . $this->request->get['filter_total'];
            }

            if (isset($this->request->get['filter_date_added'])) {
                $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
            }

            if (isset($this->request->get['filter_date_modified'])) {
                $url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
            }

            if (isset($this->request->get['sort'])) {
                $url .= '&sort=' . $this->request->get['sort'];
            }

            if (isset($this->request->get['order'])) {
                $url .= '&order=' . $this->request->get['order'];
            }

            if (isset($this->request->get['page'])) {
                $url .= '&page=' . $this->request->get['page'];
            }

            $data['breadcrumbs'] = array();

            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_home'),
                'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
            );

            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link('sale/order_distributor', 'token=' . $this->session->data['token'] . $url, 'SSL')
            );
            $data['export'] = $this->url->link('sale/order_distributor/export', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
            $data['shipping'] = $this->url->link('sale/order_distributor/shipping', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
            $data['invoice'] = $this->url->link('sale/order_distributor/invoice', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
            $data['export_order'] = $this->url->link('sale/order_distributor/exportOrderDetails', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
            
            /*编辑订单不改订单号*/
            $data['edit_order'] = $this->url->link('sale/order_distributor/editOrder', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
            /*编辑订单不改订单号*/

            $data['edit'] = $this->url->link('sale/order_distributor/edit', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
            $data['cancel'] = $this->url->link('sale/order_distributor', 'token=' . $this->session->data['token'] . $url, 'SSL');

            $data['order_id'] = $this->request->get['order_id'];
            
            $data['store_name'] = $order_info['store_name'];
            $data['store_url'] = $order_info['store_url'];

            if ($order_info['invoice_no']) {
                $data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
            } else {
                $data['invoice_no'] = '';
            }
            

            $data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));
            $data['fullname'] = $order_info['fullname'];

            /*
            if ($order_info['customer_id']) {
                $data['customer'] = $this->url->link('customer/customer/edit', 'token=' . $this->session->data['token'] . '&customer_id=' . $order_info['customer_id'], 'SSL');
            } else {
                $data['customer'] = '';
            }
            */

            $this->load->model('customer/customer_group');

            $customer_group_info = $this->model_customer_customer_group->getCustomerGroup($order_info['customer_group_id']);

            if ($customer_group_info) {
                $data['customer_group'] = $customer_group_info['name'];
            } else {
                $data['customer_group'] = '';
            }

            $data['email'] = $order_info['email'];
            $data['telephone'] = $order_info['telephone'];

            $data['is_pay'] = $order_info['is_pay']?'已付款':'未付款';
            
            $data['shipping_telephone'] = $order_info['shipping_telephone'];
            
            $data['shipping_method'] = $order_info['shipping_method'];
            $data['recommended_code'] = $order_info['recommended_code'];
            $data['payment_method'] = $order_info['payment_method'];

            // Payment Address
            if ($order_info['payment_address_format']) {
                $format = $order_info['payment_address_format'];
            } else {
                $format = '{fullname}' . "\n" . '{company}' . "\n" . '{address}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
            }

            $find = array(
                '{fullname}',
                '{company}',
                '{address}',
                '{city}',
                '{postcode}',
                '{zone}',
                '{zone_code}',
                '{country}'
            );

            $replace = array(
                'fullname'     => $order_info['payment_fullname'],
                'company'   => $order_info['payment_company'],
                'address'     => $order_info['payment_address'],
                'city'      => $order_info['payment_city'],
                'postcode'  => $order_info['payment_postcode'],
                'zone'      => $order_info['payment_zone'],
                'zone_code' => $order_info['payment_zone_code'],
                'country'   => $order_info['payment_country']
            );

            $data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

            // Shipping Address
            if ($order_info['shipping_address_format']) {
                $format = $order_info['shipping_address_format'];
            } else {
                $format = '{fullname}' . "\n" . '{company}' . "\n" . '{address}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
            }

            $find = array(
                '{fullname}',
                '{company}',
                '{address}',
                '{city}',
                '{postcode}',
                '{zone}',
                '{zone_code}',
                '{country}'
            );

            $replace = array(
                'fullname'     => $order_info['shipping_fullname'],
                'company'   => $order_info['shipping_company'],
                'address' => $order_info['shipping_address'],
                'city'      => $order_info['shipping_city'],
                'postcode'  => $order_info['shipping_postcode'],
                'zone'      => $order_info['shipping_zone'],
                'zone_code' => $order_info['shipping_zone_code'],
                'country'   => $order_info['shipping_country']
            );

            $data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

            // Uploaded files
            $this->load->model('tool/upload');

            $data['products'] = array();

            $this->load->model('catalog/vendor');
            $this->load->model('stock/stocksearch');
            $products = $this->model_sale_order->getOrderProducts($this->request->get['order_id']); 

            $total_ship_status = 1;
            foreach ($products as $product) {
                $option_data = array();

                $options = $this->model_sale_order->getOrderOptions($this->request->get['order_id'], $product['order_product_id']);

            $product_vendor_info = M('vendor')->where(array('vproduct_id'=>$product['product_id']))->field('vendor')->find();
            if($product_vendor_info) {
                $product['vendor_id'] = $product_vendor_info['vendor'];
            }
                $vname = $this->model_catalog_vendor->getVendor($product['vendor_id']);

                foreach ($options as $option) {
                    if ($option['type'] != 'file') {
                        $option_data[] = array(
                            'name'  => $option['name'],
                            'value' => $option['value'],
                            'type'  => $option['type']
                        );
                    } else {
                        $upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

                        if ($upload_info) {
                            $option_data[] = array(
                                'name'  => $option['name'],
                                'value' => $upload_info['name'],
                                'type'  => $option['type'],
                                'href'  => $this->url->link('tool/upload/download', 'token=' . $this->session->data['token'] . '&code=' . $upload_info['code'], 'SSL')
                            );
                        }
                    }
                }

                $productStock = $this->model_stock_stocksearch->getGatherQtyByProductCode($product['product_code']);
                $data['products'][] = array(
                    'order_product_id' => $product['order_product_id'],
                    'product_id'       => $product['product_id'],
                    'sku'                => $product['sku'],
                    'name'                => $product['name'],
                    'vname'            => $vname['vendor_name'],
                    'model'               => $product['model'],
                    'option'              => $option_data,
                    'ship_status'       => $product['ship_status'],
                    'quantity'           => $product['quantity'],
                    'price'               => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
                    'total'               => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']),
                    //'href'                => $this->url->link('catalog/product/edit', 'token=' . $this->session->data['token'] . '&product_id=' . $product['product_id'], 'SSL')
                    'lackQty'           => (int)$product['lack_quantity'],
                    'qtyInOnway' => $productStock['qtyInOnway'],
                );
                $total_ship_status *= $product['ship_status'];
            }

            $data['vouchers'] = array();

            $data['total_ship_status'] = $total_ship_status;
            $vouchers = $this->model_sale_order->getOrderVouchers($this->request->get['order_id']);

            foreach ($vouchers as $voucher) {
                $data['vouchers'][] = array(
                    'description' => $voucher['description'],
                    'amount'      => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']),
                    'href'        => $this->url->link('sale/voucher/edit', 'token=' . $this->session->data['token'] . '&voucher_id=' . $voucher['voucher_id'], 'SSL')
                );
            }

            $data['totals'] = array();

            $totals = $this->model_sale_order->getOrderTotals($this->request->get['order_id']);

            foreach ($totals as $total) {
                $data['totals'][] = array(
                    'title' => $total['title'],
                    'text'  => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
                );
            }

            $data['comment'] = nl2br($order_info['comment']);

            $this->load->model('customer/customer');

            $data['reward'] = $order_info['reward'];
            
            switch ($order_info['bill_status']) {
                case '0':
                    $data['is_invoice_text'] = $data['text_is_invoice_removed'];
                    break;
                case '1':
                    $data['is_invoice_text'] = $data['text_is_invoice_added'];
                    break;
                case '2':
                    $data['is_invoice_text'] = $data['text_is_invoice_passed'];
                    break;
                default:
                    # code...
                    break;
            }
            $data['is_invoice'] = $order_info['bill_status'];

            $data['reward_total'] = $this->model_customer_customer->getTotalCustomerRewardsByOrderId($this->request->get['order_id']);

            $data['affiliate_fullname'] = $order_info['affiliate_fullname'];

            if ($order_info['affiliate_id']) {
                $data['affiliate'] = $this->url->link('marketing/affiliate/edit', 'token=' . $this->session->data['token'] . '&affiliate_id=' . $order_info['affiliate_id'], 'SSL');
            } else {
                $data['affiliate'] = '';
            }

            $data['commission'] = $this->currency->format($order_info['commission'], $order_info['currency_code'], $order_info['currency_value']);

            $this->load->model('marketing/affiliate');

            $data['commission_total'] = $this->model_marketing_affiliate->getTotalTransactionsByOrderId($this->request->get['order_id']);

            $this->load->model('localisation/order_status');

            $order_status_info = $this->model_localisation_order_status->getOrderStatus($order_info['order_status_id']);

            if ($order_status_info) {
                $data['order_status'] = $order_status_info['name'];
            } else {
                $data['order_status'] = '';
            }

            $data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();

            $data['order_status_id'] = $order_info['order_status_id'];

            $data['account_custom_field'] = $order_info['custom_field'];

            $finance_group = $this->config->get('config_finance_user');
            $groupId = $this->user->getGroupId();
            $data['have_permission'] = false;
            $has_pay = $order_info['is_pay'];
            if(($groupId == $finance_group)&&(!$has_pay)){
                $data['have_permission'] = true;
            }

            // Custom Fields
            $this->load->model('customer/custom_field');
            
            $data['account_custom_fields'] = array();

            $filter_data = array(
                'sort'  => 'cf.sort_order',
                'order' => 'ASC',
            );

            $custom_fields = $this->model_customer_custom_field->getCustomFields($filter_data);

            foreach ($custom_fields as $custom_field) {
                if ($custom_field['location'] == 'account' && isset($order_info['custom_field'][$custom_field['custom_field_id']])) {
                    if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
                        $custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['custom_field'][$custom_field['custom_field_id']]);
                        
                        if ($custom_field_value_info) {
                            $data['account_custom_fields'][] = array(
                                'name'  => $custom_field['name'],
                                'value' => $custom_field_value_info['name']
                            );
                        }
                    }
                    
                    if ($custom_field['type'] == 'checkbox' && is_array($order_info['custom_field'][$custom_field['custom_field_id']])) {
                        foreach ($order_info['custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
                            $custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);
                            
                            if ($custom_field_value_info) {                        
                                $data['account_custom_fields'][] = array(
                                    'name'  => $custom_field['name'],
                                    'value' => $custom_field_value_info['name']
                                );    
                            }
                        }
                    }
                                        
                    if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
                        $data['account_custom_fields'][] = array(
                            'name'  => $custom_field['name'],
                            'value' => $order_info['custom_field'][$custom_field['custom_field_id']]
                        );                        
                    }
                    
                    if ($custom_field['type'] == 'file') {
                        $upload_info = $this->model_tool_upload->getUploadByCode($order_info['custom_field'][$custom_field['custom_field_id']]);

                        if ($upload_info) {
                            $data['account_custom_fields'][] = array(
                                'name'  => $custom_field['name'],
                                'value' => $upload_info['name']
                            );                            
                        }
                    }
                }
            }
            
            // Custom fields
            $data['payment_custom_fields'] = array();

            foreach ($custom_fields as $custom_field) {
                if ($custom_field['location'] == 'address' && isset($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                    if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
                        $custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['payment_custom_field'][$custom_field['custom_field_id']]);

                        if ($custom_field_value_info) {
                            $data['payment_custom_fields'][] = array(
                                'name'  => $custom_field['name'],
                                'value' => $custom_field_value_info['name'],
                                'sort_order' => $custom_field['sort_order']
                            );
                        }
                    }

                    if ($custom_field['type'] == 'checkbox' && is_array($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
                        foreach ($order_info['payment_custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
                            $custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);

                            if ($custom_field_value_info) {
                                $data['payment_custom_fields'][] = array(
                                    'name'  => $custom_field['name'],
                                    'value' => $custom_field_value_info['name'],
                                    'sort_order' => $custom_field['sort_order']
                                );
                            }
                        }
                    }

                    if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
                        $data['payment_custom_fields'][] = array(
                            'name'  => $custom_field['name'],
                            'value' => $order_info['payment_custom_field'][$custom_field['custom_field_id']],
                            'sort_order' => $custom_field['sort_order']
                        );
                    }

                    if ($custom_field['type'] == 'file') {
                        $upload_info = $this->model_tool_upload->getUploadByCode($order_info['payment_custom_field'][$custom_field['custom_field_id']]);

                        if ($upload_info) {
                            $data['payment_custom_fields'][] = array(
                                'name'  => $custom_field['name'],
                                'value' => $upload_info['name'],
                                'sort_order' => $custom_field['sort_order']
                            );
                        }
                    }
                }
            }            
            
            // Shipping            
            $data['shipping_custom_fields'] = array();

            foreach ($custom_fields as $custom_field) {
                if ($custom_field['location'] == 'address' && isset($order_info['shipping_custom_field'][$custom_field['custom_field_id']])) {
                    if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
                        $custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['shipping_custom_field'][$custom_field['custom_field_id']]);

                        if ($custom_field_value_info) {
                            $data['shipping_custom_fields'][] = array(
                                'name'  => $custom_field['name'],
                                'value' => $custom_field_value_info['name'],
                                'sort_order' => $custom_field['sort_order']
                            );
                        }
                    }

                    if ($custom_field['type'] == 'checkbox' && is_array($order_info['shipping_custom_field'][$custom_field['custom_field_id']])) {
                        foreach ($order_info['shipping_custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
                            $custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);

                            if ($custom_field_value_info) {
                                $data['shipping_custom_fields'][] = array(
                                    'name'  => $custom_field['name'],
                                    'value' => $custom_field_value_info['name'],
                                    'sort_order' => $custom_field['sort_order']
                                );
                            }
                        }
                    }

                    if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
                        $data['shipping_custom_fields'][] = array(
                            'name'  => $custom_field['name'],
                            'value' => $order_info['shipping_custom_field'][$custom_field['custom_field_id']],
                            'sort_order' => $custom_field['sort_order']
                        );
                    }

                    if ($custom_field['type'] == 'file') {
                        $upload_info = $this->model_tool_upload->getUploadByCode($order_info['shipping_custom_field'][$custom_field['custom_field_id']]);

                        if ($upload_info) {
                            $data['shipping_custom_fields'][] = array(
                                'name'  => $custom_field['name'],
                                'value' => $upload_info['name'],
                                'sort_order' => $custom_field['sort_order']
                            );
                        }
                    }
                }
            }                

            $data['ip'] = $order_info['ip'];
            $data['forwarded_ip'] = $order_info['forwarded_ip'];
            $data['user_agent'] = $order_info['user_agent'];
            $data['accept_language'] = $order_info['accept_language'];

            // Additional Tabs
            $data['tabs'] = array();

            $this->load->model('extension/extension');

            $content = $this->load->controller('payment/' . $order_info['payment_code'] . '/order');

            if ($content) {
                $this->load->language('payment/' . $order_info['payment_code']);

                $data['tabs'][] = array(
                    'code'    => $order_info['payment_code'],
                    'title'   => $this->language->get('heading_title'),
                    'content' => $content
                );
            }

            $extensions = $this->model_extension_extension->getInstalled('fraud');

            foreach ($extensions as $extension) {
                if ($this->config->get($extension . '_status')) {
                    $this->load->language('fraud/' . $extension);

                    $content = $this->load->controller('fraud/' . $extension . '/order');

                    if ($content) {
                        $data['tabs'][] = array(
                            'code'    => $extension,
                            'title'   => $this->language->get('heading_title'),
                            'content' => $content
                        );
                    }
                }
            }

            // API login
            $this->load->model('user/api');

            $api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));

            if ($api_info) {
                $data['api_id'] = $api_info['api_id'];
                $data['api_key'] = $api_info['key'];
                $data['api_ip'] = $this->request->server['REMOTE_ADDR'];
            } else {
                $data['api_id'] = '';
                $data['api_key'] = '';
                $data['api_ip'] = '';
            }

            //$data['tradeno_status'] = $this->model_sale_order->gettradeNo($order_id);
            
            $data['header'] = $this->load->controller('common/header');
            $data['column_left'] = $this->load->controller('common/column_left');
            $data['footer'] = $this->load->controller('common/footer');

            $this->response->setOutput($this->load->view('sale/order_info_distributor.tpl', $data));
        } else {
            $this->load->language('error/not_found');

            $this->document->setTitle($this->language->get('heading_title'));

            $data['heading_title'] = $this->language->get('heading_title');

            $data['text_not_found'] = $this->language->get('text_not_found');

            $data['breadcrumbs'] = array();

            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_home'),
                'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
            );

            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
            );

            $data['header'] = $this->load->controller('common/header');
            $data['column_left'] = $this->load->controller('common/column_left');
            $data['footer'] = $this->load->controller('common/footer');

            $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
        }
    }

    public function history() {
        $this->load->language('sale/order');

        $data['text_no_results'] = $this->language->get('text_no_results');

        $data['column_date_added'] = $this->language->get('column_date_added');
        $data['column_status'] = $this->language->get('column_status');
        $data['column_notify'] = $this->language->get('column_notify');
        $data['column_comment'] = $this->language->get('column_comment');

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }
        $limit = 10;

        $data['histories'] = array();

        $this->load->model('sale/order');

        $results = $this->model_sale_order->getOrderHistories($this->request->get['order_id'], ($page - 1) * $limit, $limit);

        foreach ($results as $result) {
            $data['histories'][] = array(
                'notify'     => $result['notify'] ? $this->language->get('text_yes') : $this->language->get('text_no'),
                'status'     => $result['status'],
                'comment'    => nl2br($result['comment']),
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
            );
        }

        $history_total = $this->model_sale_order->getTotalOrderHistories($this->request->get['order_id']);

        $pagination = new Pagination();
        $pagination->total = $history_total;
        $pagination->page = $page;
        $pagination->limit = $limit;
        $pagination->url = $this->url->link('sale/order_distributor/history', 'token=' . $this->session->data['token'] . '&order_id=' . $this->request->get['order_id'] . '&page={page}', 'SSL');

        $data['pagination'] = $pagination->render();

        $data['results'] = sprintf($this->language->get('text_pagination'), ($history_total) ? (($page - 1) * $limit) + 1 : 0, ((($page - 1) * $limit) > ($history_total - $limit)) ? $history_total : ((($page - 1) * $limit) + $limit), $history_total, ceil($history_total / $limit));

        $this->response->setOutput($this->load->view('sale/order_history_distributor.tpl', $data));
    }

    public function exportLists(){
        if (isset($this->request->get['filter_order_id'])) {
            $filter_order_id = $this->request->get['filter_order_id'];
        } else {
            $filter_order_id = null;
        }

        if (isset($this->request->get['filter_customer'])) {
            $filter_customer = $this->request->get['filter_customer'];
        } else {
            $filter_customer = null;
        }

        if (isset($this->request->get['filter_order_status'])) {
            $filter_order_status = $this->request->get['filter_order_status'];
        } else {
            $filter_order_status = null;
        }

        if (isset($this->request->get['filter_total'])) {
            $filter_total = $this->request->get['filter_total'];
        } else {
            $filter_total = null;
        }

        if (isset($this->request->get['filter_is_pay'])) {
            $filter_is_pay = $this->request->get['filter_is_pay'];
        } else {
            $filter_is_pay = 3;
        }

        if (isset($this->request->get['filter_date_added'])) {
            $filter_date_added = $this->request->get['filter_date_added'];
        } else {
            $filter_date_added = null;
        }

        if (isset($this->request->get['filter_date_modified'])) {
            $filter_date_modified = $this->request->get['filter_date_modified'];
        } else {
            $filter_date_modified = null;
        }

        if (isset($this->request->get['filter_date_start'])) {
            $filter_date_start = $this->request->get['filter_date_start'];
        } else {
            $filter_date_start = null;
        }

        if (isset($this->request->get['filter_date_end'])) {
            $filter_date_end = $this->request->get['filter_date_end'];
        } else {
            $filter_date_end = null;
        }

        if (isset($this->request->get['filter_logcenter'])) {
            $filter_logcenter = $this->request->get['filter_logcenter'];
        } else {
            $filter_logcenter = null;
        }

        if (isset($this->request->get['filter_recommended_code'])) {
            $filter_recommended_code = (string)$this->request->get['filter_recommended_code'];
        } else {
            $filter_recommended_code = null;
        }

        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'o.order_id';
        }

        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            $order = 'DESC';
        }

        $filter_data = array(
            'filter_order_id'      => $filter_order_id,
            'filter_customer'      => $filter_customer,
            'filter_order_status'  => $filter_order_status,
            'filter_total'         => $filter_total,
            'filter_is_pay'        => $filter_is_pay,
            'filter_date_added'    => $filter_date_added,
            'filter_date_modified' => $filter_date_modified,
            'filter_logcenter'     => $filter_logcenter,
            'filter_date_start'    => $filter_date_start,
            'filter_date_end'      => $filter_date_end,
            'filter_user_id'       => $this->user->getId(),
            'filter_recommended_code'      => $filter_recommended_code,
            'sort'                 => $sort,
            'order'                => $order,
        );

        $this->load->model('sale/order');

        $results = $this->model_sale_order->getExportOrders($filter_data);

        $bill_array = array(
            '1'=>'未开发票',
            '2'=>'已开发票',
            '0'=>'不需要开发票',
        );

        foreach ($results as $result) {
            if($result['product_type'] != 2){
                $data[] = array(
                    'order_id'          => $result['order_id'],
                    'customer'          => $result['customer'],
                    'status'            => $result['status'],
                    'total'             => $result['total'],
                    'date_added'        => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                    'date_modified'     => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                    'bill_status'       => $bill_array[$result['bill_status']],
                    'recommended_code'  => $result['recommended_code'],
                    'vendor_name'       => $result['vendor_name'],
                    'product_name'      => $result['product_name'],
                    'product_code'              => $result['product_code'],
                    'sku'               => $result['sku'],
                    'shipping_country'  => $result['shipping_country'],
                    'shipping_zone'     => $result['shipping_zone'],
                    'model'             => $result['model'],
                    'quantity'          => $result['quantity'],
                    'lack_quantity'     => $result['lack_quantity'],
                    'price'             => $result['price'],
                    'cd_name'           => $result['cd_name'],
                    'telephone'         => $result['telephone'],
                    'ship_status'       => $result['ship_status']?'已发货':'未发货',
                    'shipping_address'  => $result['shipping_address'],
                    'is_pay'            => $result['is_pay']?'已付款':'未付款',
                    'payment_method'    => $result['payment_method'],
                    'paid_time'         => $result['paid_time'],
                    'auditted_time'     => $result['auditted_time'],
                    'delivered_time'    => $result['delivered_time'],
                    'completed_time'    => $result['completed_time'],
                    'out_time'          => $result['out_time'],
                    'product_cost'      => $result['product_cost'],
                    'profit'            => (round(floatval(($result['price'] - $result['product_cost'])/$result['product_cost']),2)*100).'%'
                );
            }else{
                $sub_results = $this->model_sale_order->getExportCombineProduct($result['order_product_id']);
                foreach($sub_results as $sub_result){
                    $data[] = array(
                        'order_id'          => $result['order_id'],
                        'customer'          => $result['customer'],
                        'status'            => $result['status'],
                        'total'             => $sub_result['total'],
                        'date_added'        => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                        'date_modified'     => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                        'bill_status'       => $bill_array[$result['bill_status']],
                        'recommended_code'  => $result['recommended_code'],
                        'vendor_name'       => $sub_result['vsname'],
                        'product_name'      => $sub_result['pdname'].'('.$result['product_name'].')',
                        'product_code'              => $sub_result['product_code'],
                        'sku'               => $sub_result['sku'],
                        'shipping_country'  => $result['shipping_country'],
                        'shipping_zone'     => $result['shipping_zone'],
                        'model'             => $sub_result['model'],
                        'quantity'          => $sub_result['quantity'],
                        'lack_quantity'     => $sub_result['lack_quantity'],
                        'price'             => $sub_result['price'],
                        'cd_name'           => $sub_result['cdname'],
                        'telephone'         => $result['telephone'],
                        'ship_status'       => $result['ship_status']?'已发货':'未发货',
                        'shipping_address'  => $result['shipping_address'],
                        'is_pay'            => $result['is_pay']?'已付款':'未付款',
                        'payment_method'    => $result['payment_method'],
                        'paid_time'         => $result['paid_time'],
                        'auditted_time'     => $result['auditted_time'],
                        'delivered_time'    => $result['delivered_time'],
                        'completed_time'    => $result['completed_time'],
                        'out_time'          => $result['out_time'],
                        'product_cost'      => $sub_result['product_cost'],
                        'profit'            => (round(floatval(($sub_result['price'] - $sub_result['product_cost'])/$sub_result['product_cost']),2)*100).'%'
                    );
                }
            }
        }

        $this->load->library('PHPExcel/PHPExcel');
        $objPHPExcel = new PHPExcel();    
        $objProps = $objPHPExcel->getProperties();    
        $objProps->setCreator("Think-tec");
        $objProps->setLastModifiedBy("Think-tec");    
        $objProps->setTitle("Think-tec Contact");    
        $objProps->setSubject("Think-tec Contact Data");    
        $objProps->setDescription("Think-tec Contact Data");    
        $objProps->setKeywords("Think-tec Contact");    
        $objProps->setCategory("Think-tec");
        $objPHPExcel->setActiveSheetIndex(0);     
        $objActSheet = $objPHPExcel->getActiveSheet(); 
           
        $objActSheet->setTitle('Sheet1');
        $col_idx = 'A';
        $headers = array( '订单日期',  '订单ID',  '会员手机号','会员信息','商品名称',   '品牌产商', '商品编码',    '条形码','型号', '数量','缺货数量',     '单品价格','单品小计','单品成本','单品毛利率','订单状态',  '开票状态',  '邀请码',         '省市',              '市县','详细地址','分类','商品发货状态','付款状态','付款方式','支付时间','审核时间','出库时间','派送时间','完成时间');
        $row_keys = array('date_added','order_id','telephone', 'customer','product_name','vendor_name', 'product_code', 'sku',   'model','quantity','lack_quantity','price',  'total', 'product_cost','profit',  'status','bill_status','recommended_code','shipping_country','shipping_zone','shipping_address','cd_name','ship_status','is_pay','payment_method','paid_time','auditted_time','out_time','delivered_time','completed_time');
        foreach ($headers as $header) {
          $objActSheet->setCellValue($col_idx++.'1', $header);  
        }
        //添加物流信息
        $i = 2;
        foreach ($data as $rlst) {
          $col_idx = 'A';
          foreach ($row_keys as $rk) {
            $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
          }
          $i++;
        } 

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        
        ob_end_clean();
        // Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="order_'.date('Y-m-d',time()).'.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objWriter->save('php://output'); 
        exit;

    }

    public function exportCollect(){
        if (isset($this->request->get['filter_order_id'])) {
            $filter_order_id = $this->request->get['filter_order_id'];
        } else {
            $filter_order_id = null;
        }

        if (isset($this->request->get['filter_customer'])) {
            $filter_customer = $this->request->get['filter_customer'];
        } else {
            $filter_customer = null;
        }

        if (isset($this->request->get['filter_order_status'])) {
            $filter_order_status = $this->request->get['filter_order_status'];
        } else {
            $filter_order_status = null;
        }

        if (isset($this->request->get['filter_verify_status'])) {
            $filter_verify_status = $this->request->get['filter_verify_status'];
        } else {
            $filter_verify_status = null;
        }

        if (isset($this->request->get['filter_total'])) {
            $filter_total = $this->request->get['filter_total'];
        } else {
            $filter_total = null;
        }

        if (isset($this->request->get['filter_is_pay'])) {
            $filter_is_pay = $this->request->get['filter_is_pay'];
        } else {
            $filter_is_pay = '';
        }

        if (isset($this->request->get['filter_date_added'])) {
            $filter_date_added = $this->request->get['filter_date_added'];
        } else {
            $filter_date_added = null;
        }

        if (isset($this->request->get['filter_date_modified'])) {
            $filter_date_modified = $this->request->get['filter_date_modified'];
        } else {
            $filter_date_modified = null;
        }

        if (isset($this->request->get['filter_date_start'])) {
            $filter_date_start = $this->request->get['filter_date_start'];
        } else {
            $filter_date_start = null;
        }

        if (isset($this->request->get['filter_date_end'])) {
            $filter_date_end = $this->request->get['filter_date_end'];
        } else {
            $filter_date_end = null;
        }

        if (isset($this->request->get['filter_logcenter'])) {
            $filter_logcenter = $this->request->get['filter_logcenter'];
        } else {
            $filter_logcenter = null;
        }

        if (isset($this->request->get['filter_recommended_code'])) {
            $filter_recommended_code = $this->request->get['filter_recommended_code'];
        } else {
            $filter_recommended_code = null;
        }

        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'o.order_id';
        }

        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            $order = 'DESC';
        }

        $filter_data = array(
            'filter_order_id'      => $filter_order_id,
            'filter_customer'      => $filter_customer,
            'filter_order_status'  => $filter_order_status,
            'filter_verify_status' => $filter_verify_status,
            'filter_total'         => $filter_total,
            'filter_date_added'    => $filter_date_added,
            'filter_date_modified' => $filter_date_modified,
            'filter_logcenter'     => $filter_logcenter,
            'filter_is_pay'        => $filter_is_pay,
            'filter_date_start'    => $filter_date_start,
            'filter_date_end'      => $filter_date_end,
            'filter_recommended_code'      => $filter_recommended_code,
            'filter_user_id'       => $this->user->getId(),
            'sort'                 => $sort,
            'order'                => $order,
        );
        $this->load->model('sale/order');

        $results = $this->model_sale_order->getOrders($filter_data);
        foreach ($results as $result) {
            $save_data[] = array(
                'order_id'      => $result['order_id'],
                'shipping_company'=> $result['shipping_company'],
                'customer'      => $result['customer'],
                'status'        => $result['status'],
                'verify_status' => intval($result['verify_status'])?(intval($result['verify_status'])==1?'已审核(缺货)':'已审核'):'未审核',
                'shipping_zone' => $result['shipping_zone'],
                'shipping_country'=>$result['shipping_country'],
                'recommended_code'=>$result['recommended_code'],
                'recommended_name'=>$result['recommended_name'],
                'bill_status'   => $bill_array[$result['bill_status']],
                'total'         => number_format($result['total'],2,'.',''),
                'value'         => number_format($result['value'],2,'.',''),
                'date_added'    => date('Y-m-d h:i', strtotime($result['date_added'])),
                'is_pay'        =>$result['is_pay']?'已付款':'未付款',
                'payment_method'=>$result['payment_method'],
                'paid_time'     =>$result['paid_time'],
                'auditted_time' =>$result['auditted_time'],
                'out_time'      =>$result['out_time'],
                'delivered_time'=>$result['delivered_time'],
                'completed_time'=>$result['completed_time']
            );
        }
    $headers = array('订单号','会员','状态','审核状态','原价单品小计','单品小计','下单日期','开票状态','超市名称','邀请码','客户经理姓名','省市','市县','付款状态','支付方式','支付时间','审核时间','出库时间','派送时间','完成时间');
    $row_keys = array('order_id','customer','status','verify_status','value','total','date_added','bill_status','shipping_company','recommended_code','recommended_name','shipping_country','shipping_zone','is_pay','payment_method','paid_time','auditted_time','out_time','delivered_time','completed_time');

    $this->load->helper('export');
    prepareDownloadExcel($save_data, $headers, $row_keys, 'Orders');
    }
}
